package com.hibernate.dao;


import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.hibernate.model.Person;
import com.hibernate.utils.HibernateUtil;

import java.util.List;

public class PersonDAO
{
	public static void save(Person person)
	{
		Session session = 
				HibernateUtil.currentSession();
		
		Transaction tx = session.beginTransaction();
		
		try
		{
			session.save(person);
			tx.commit();
		}
		catch(Exception ex)
		{
			if(null != tx)
			{
				tx.rollback();
			}
		}
		finally
		{
			HibernateUtil.closeSession(session);
		}
	}
	
	
	public static List<Person> listAll()
	{
		Session session = 
				HibernateUtil.currentSession();
		
		List<Person> l = null;
		
		try
		{
			l = session.createCriteria(Person.class).list();
		
			
			//l = session.createCriteria(Person.class)
			//	.add(Restrictions.eq("username", "lix2")).list();
		}
		catch(Exception ex)
		{
			
		}
		
		return l;
	}
	
	public static void delete(int id)
	{
		Session session = 
				HibernateUtil.currentSession();
		
		Transaction tx = session.beginTransaction();
		
		Person p = (Person)session.get(Person.class, id);
		session.delete(p);
		
		tx.commit();
	}
	
	
	public static Person get(int id)
	{
		Session session = 
				HibernateUtil.currentSession();
		
		Person p = (Person)session.get(Person.class, id);
		
		return p;
	}
	
	
	public static void main(String[] args)
	{
		Person p = new Person();
		p.setUsername("lix112");
		p.setPassword("admin");
		p.setAge(23);
		
		p.setRegisterDate(new java.util.Date());
		
		PersonDAO.save(p);
	}
	
	
}
